package com.bill99.codecheck.sonar.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.bill99.codecheck.sonar.orm.entity.JiraItem;
import com.bill99.codecheck.sonar.orm.entity.RnmItem;
import com.bill99.codecheck.sonar.orm.entity.SonarLogItem;
import com.bill99.codecheck.sonar.orm.entity.SvnauthItem;
import com.bill99.codecheck.sonar.orm.manager.JiraDataMng;
import com.bill99.codecheck.sonar.orm.manager.QampSonarlogMng;
import com.bill99.codecheck.sonar.orm.manager.SvnauthMng;
import com.bill99.codecheck.sonar.service.ElmDataService;
import com.bill99.codecheck.sonar.service.GenerateBuildXmlService;
import com.bill99.codecheck.sonar.service.PerFormAntXmlService;
import com.bill99.codecheck.sonar.service.SonarEmailService;
import com.bill99.codecheck.sonar.service.SonarProcessService;
import com.bill99.codecheck.sonar.service.SvnCheckOutService;
import com.bill99.codecheck.tools.TranEncodeTool;
import com.bill99.riaframework.common.dto.DataStatisticsDto;
import com.bill99.riaframework.common.helper.Bill99Logger;
import com.bill99.riaframework.domain.mail.EmailSender;
import com.sun.xml.internal.ws.util.StringUtils;

public class SonarProcessServiceImpl implements SonarProcessService {
	private Bill99Logger logger = Bill99Logger.getLogger(this.getClass());

	private ElmDataService elmData;
	private SvnCheckOutService svnCheckOut;
	private PerFormAntXmlService perFormAntXml;
	private SonarEmailService sonarEmailService;
	private String ccAddress;

	private Boolean isTest;

	private GenerateBuildXmlService generateBuildXmlService;

	public void setGenerateBuildXmlService(GenerateBuildXmlService generateBuildXmlService) {
		this.generateBuildXmlService = generateBuildXmlService;
	}

	public void setCcAddress(String ccAddress) {
		this.ccAddress = ccAddress;
	}

	public void setSonarEmailService(SonarEmailService sonarEmailService) {
		this.sonarEmailService = sonarEmailService;
	}

	private EmailSender emailSender;
	private JiraDataMng jiraMng;
	private QampSonarlogMng qampsonarlogMng;
	private SvnauthMng svnauthMng;
	

	public void setSvnauthMng(SvnauthMng svnauthMng) {
		this.svnauthMng = svnauthMng;
	}

	public void setJiraMng(JiraDataMng jiraMng) {
		this.jiraMng = jiraMng;
	}

	public void setQampsonarlogMng(QampSonarlogMng qampsonarlogMng) {
		this.qampsonarlogMng = qampsonarlogMng;
	}

	public void setElmData(ElmDataService elmData) {
		this.elmData = elmData;
	}

	public void setSvnCheckOut(SvnCheckOutService svnCheckOut) {
		this.svnCheckOut = svnCheckOut;
	}

	public void setPerFormAntXml(PerFormAntXmlService perFormAntXml) {
		this.perFormAntXml = perFormAntXml;
	}

	@Override
	public void sonarDeal() {
		//从elm库获取数据
		logger.info("从elm库获取数据");
		Map<String, List<RnmItem>> dealDataMap = elmData.elmDealData();
		List<RnmItem> rnmItemList = null;
		for (Entry<String, List<RnmItem>> rnmItemMap : dealDataMap.entrySet()) {
			rnmItemList = rnmItemMap.getValue();
			if (rnmItemList.size() > 0) {
				sonarDeal4One(rnmItemMap.getKey(), rnmItemList);
			}
		}

	}

	private void sonarDeal4One(String taskemailString, List<RnmItem> rnmItemList) {
		try {
			String targetName = "";
			String dealxmlPath = "";
			//svn 提交代码者
			String username = taskemailString;
			RnmItem rnmItemmsg = new RnmItem();
			Set<String> releaseIdSet = new HashSet<String>();
			logger.info("从SVN checkout代码");
			for (RnmItem rnmItem : rnmItemList) {
				if (rnmItem.getSvnPath() != null && rnmItem.getTempfilePath() != null) {
					svnCheckOut.svnCheckOut(rnmItem.getSvnPath(), rnmItem.getTempfilePath());
					TranEncodeTool.tranEncode(rnmItem.getTranEncodePath());
				}
				targetName = rnmItem.getSonarjobName().replace(".", "").replace("@", "").replace("99billcom", "");
				//				xmlPath = rnmItem.getBuildPath();
				dealxmlPath = rnmItem.getDealbuildxmlPath();

				if (StringUtils.hasLength(rnmItem.getReleaseId())) {
					releaseIdSet.add(rnmItem.getReleaseId());//本次扫描涉及的上线ID集合
				}
			}
			boolean resultflag = generateBuildXmlService.generateXml(targetName, dealxmlPath);
			if (resultflag) {
				logger.info("执行Ant 脚本");
				rnmItemmsg = perFormAntXml.perFormAntXml(dealxmlPath);
				//记录日志
				logger.info("记录日志");
				SonarLogItem sonarLogItem = new SonarLogItem();
				sonarLogItem.setSonartaskid(targetName);

				if (!"".equals(rnmItemmsg.getInfoMsg())) {
					sonarLogItem.setInfomsg(rnmItemmsg.getInfoMsg());
				}

				if (!"".equals(rnmItemmsg.getErrMsg())) {
					sonarLogItem.setErrmsg(rnmItemmsg.getErrMsg());
				}
				qampsonarlogMng.saveSonarLog(sonarLogItem);
			}
			//根据author email 从jira 获取 所属组及project manager email 和TestLeader email
			logger.info("根据author email 从jira 获取TL&PM email");
			JiraItem jiraitem = jiraMng.findJiraInfo(taskemailString);

			logger.info("拼装email content");
			DataStatisticsDto dataStatisticsDto = sonarEmailService.getSonarEmailHtmlContent(targetName, releaseIdSet);
           
			
			
			List<String> recvAddress = new ArrayList<String>();
			List<String> ccAddressList = new ArrayList<String>();

			recvAddress.add("lory.shi@99bill.com");
			ccAddressList.add("lory.shi@99bill.com");
			if (StringUtils.hasLength(ccAddress)) {
				ccAddressList.addAll(Arrays.asList(ccAddress.split(",")));
			}

			String name = "";
			if (!"".equals(jiraitem.getAuthorName())) {
				name = jiraitem.getAuthorName().split("\\|")[0];
			}
			String projectname = "";
			if (jiraitem.getProjectNameList().size() > 0) {
				projectname = jiraitem.getProjectNameList().get(0);
			}
			SvnauthItem  svnauthItem = null;
			String departname ="";
			if("".equals(name)){
				logger.info("外包人员jira无fullname");
				svnauthItem =  svnauthMng.getSvnInfo(taskemailString);
				name = svnauthItem.getFullname();
				taskemailString = svnauthItem.getEmail();
				departname = svnauthItem.getDepartment();
			}
			if("".equals(projectname)){
				logger.info("外包人员jira无部门");
				projectname = svnauthItem.getDepartment();
			}
			 
			//记录Sonar 执行结果至 qamp t_sonarresult_count 表中
			logger.info("记录sonar结果至表中");
			dataStatisticsDto.setSonartaskid(targetName);
			dataStatisticsDto.setDepartment(projectname);
			dataStatisticsDto.setFullname(name);
			dataStatisticsDto.setUsername(username);
			qampsonarlogMng.saveSonarResultCount(dataStatisticsDto);

			//放开 email

			if (isTest && (projectname.contains("CAP") || projectname.contains("FSC"))) {
			if (jiraitem.getEmailList()!= null && jiraitem.getEmailList().size() > 0) {
					recvAddress.addAll(jiraitem.getEmailList());
				}
			else{
				if(StringUtils.hasLength(departname)){
					String [] departn = departname.split("-|_");
					// departname 大于1
					if(departn.length > 1){
						logger.info("外包人员通过项目组获取email");
						recvAddress.addAll(jiraMng.getwaibaoJiraemailList(departn[1]));
					}
				}
				
			}
			
				recvAddress.add(taskemailString);//dev email
			}
			
				
				
			String content = dataStatisticsDto.getEmailContent();
			if (StringUtils.hasLength(content)) {
				logger.info("开始发送邮件");
				emailSender.sendEmail(recvAddress, ccAddressList, "loryTest", content, "poa_qa_tp@99bill.com");
			}
			logger.info("代码检查完成");

		} catch (Exception e) {
			logger.info("扫描异常");
			logger.error(e);
		}
	}

	public void setEmailSender(EmailSender emailSender) {
		this.emailSender = emailSender;
	}

	public void setIsTest(Boolean isTest) {
		this.isTest = isTest;
	}

}
